package com.lenovo.smarttraffic.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.InitApp;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.Sensor;
import com.lenovo.smarttraffic.bean.EnvironmentBean;
import com.lenovo.smarttraffic.bean.LineChatBean;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * on 2020-07-21
 * at 14:20
 *
 * @author Caleb.F
 * @Description
 */
public class LineChatFragment extends Fragment {
    private LineChart mMyLineChat;
    private Sensor sensorName;
    private ScheduledFuture<?> reStoreData;
    private static final String TAG = "LineChatFragment";


    public static LineChatFragment newFragment(ArrayList<EnvironmentBean> beans, Sensor sensorName) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(Constant.LINECHAT_ARGUMENT_DATA, beans);
        bundle.putSerializable(Constant.LINECHAT_ARGUMENT_NAME, sensorName);
        LineChatFragment lineChatFragment = new LineChatFragment();
        lineChatFragment.setArguments(bundle);
        return lineChatFragment;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragmment_linechat, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mMyLineChat = view.findViewById(R.id.my_line_chat);
        ArrayList<EnvironmentBean> mLineChatBean = getArguments().getParcelableArrayList(Constant.LINECHAT_ARGUMENT_DATA);
        setSensorName((Sensor) getArguments().getSerializable(Constant.LINECHAT_ARGUMENT_NAME));
        initChat();
        drawChat(handleData(mLineChatBean, sensorName));
        getData();
    }



    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    ArrayList<EnvironmentBean> beans = (ArrayList<EnvironmentBean>) msg.obj;
                    drawChat(handleData(beans,getSensorName()));
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 通过线程池获取数据
     */
    private void getData() {
        Runnable getDataRunable = new Runnable() {
            @Override
            public void run() {
                List<EnvironmentBean> all = LitePal.findAll(EnvironmentBean.class);
                Message message = new Message();
                message.what = 1;
                message.obj = all;
                handler.sendMessage(message);

            }

        };
        reStoreData = InitApp.getThreadPoolExecutor().
                scheduleWithFixedDelay(
                        getDataRunable, 0, 3, TimeUnit.SECONDS);
    }


    /**
     * 绘制界面
     *
     * @param lineChatBean
     */
    private void drawChat(LineChatBean lineChatBean) {
        if (lineChatBean == null) {
            return;
        }
        List<Entry> dataList = lineChatBean.getDataList();
        List<String> timeList = lineChatBean.getTimeList();
        if (dataList.isEmpty() || timeList.isEmpty()) {
            return;
        }

        //处理x轴显示
        XAxis xAxis = mMyLineChat.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //x轴各个之间的距离
        xAxis.setGranularity(1);
        xAxis.setLabelRotationAngle(90f);
        xAxis.setLabelCount(timeList.size());
        xAxis.setTextSize(16f);
        xAxis.setValueFormatter(
                new IAxisValueFormatter() {
                    @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                        int index = Math.round(value);
                        if (index < 0 || index >= timeList.size() || index != (int) value) {
                            return "";
                        }
                        return timeList.get(index);
                    }
                }

        );
        LineDataSet lineDataSet = new LineDataSet(dataList, "");
        lineDataSet.setColor(Color.GRAY);
        lineDataSet.setDrawCircles(true);
        lineDataSet.setCircleRadius(6f);
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setCircleColor(Color.DKGRAY);
        lineDataSet.setLineWidth(4f);
        lineDataSet.setDrawValues(false);

        LineData lineData = new LineData(lineDataSet);
        mMyLineChat.setData(lineData);
        mMyLineChat.invalidate();
    }


    private void initChat() {
        mMyLineChat.setDrawGridBackground(false);
        mMyLineChat.getXAxis().setDrawAxisLine(false);
        //禁止拉伸和滑动
        mMyLineChat.setScaleEnabled(false);
        mMyLineChat.setDragEnabled(false);
        //禁用legend
        Legend legend = mMyLineChat.getLegend();
        legend.setEnabled(false);
        YAxis axisLeft = mMyLineChat.getAxisLeft();
        axisLeft.setDrawAxisLine(true);
        axisLeft.setAxisMinimum(0f);
        YAxis axisRight = mMyLineChat.getAxisRight();
        axisRight.setAxisMinimum(0f);
        axisRight.setEnabled(false);

    }

    /**
     * 处理数据
     *
     * @param beans
     * @param sensorName
     */
    private LineChatBean handleData(ArrayList<EnvironmentBean> beans, Sensor sensorName) {
        ArrayList<Integer> mdataList = new ArrayList<>();
        ArrayList<String> mtimeList = new ArrayList<>();
        if (beans == null || sensorName == null || beans.isEmpty()) {
            return null;
        }
        for (EnvironmentBean environmentBean : beans) {
            mtimeList.add(environmentBean.getCurrentTime());
            switch (sensorName) {
                case Tem:
                    mdataList.add(environmentBean.getTem());
                    break;
                case Hum:
                    mdataList.add(environmentBean.getHum());
                    break;
                case Light:
                    mdataList.add(environmentBean.getLight());
                    break;
                case pm2_5:
                    mdataList.add(environmentBean.getPm());
                    break;
                case carbon:
                    mdataList.add(environmentBean.getCo());
                    break;
                case road_status:
                    mdataList.add(environmentBean.getRoadStatus());
                    break;
                default:
                    break;
            }
        }
        //处理数据
        ArrayList<Entry> entries = new ArrayList<>();
        for (int i = 0; i < mdataList.size(); i++) {
            entries.add(new Entry(i, (float) mdataList.get(i)));
        }
        LineChatBean lineChatBean = new LineChatBean(entries, mtimeList);
        return lineChatBean;
    }

    public Sensor getSensorName() {
        return sensorName;
    }

    public void setSensorName(Sensor sensorName) {
        this.sensorName = sensorName;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        reStoreData.cancel(true);
    }


}
